<template>
  <div class="card-padding">
    <el-form label-width="100px" :model="searchForm" :rules="rules" ref="exportTmRef">
      <el-form-item label="时间范围" prop="timeRange" >
        <el-col :span="13">
          <el-date-picker
            style="width: 90%"
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
          />
        </el-col>        
      </el-form-item>
      <el-form-item label="遥测量" prop="names">
        <el-col :span="12">
          <el-cascader
              v-model="searchForm.names"
              placeholder="请选择"
              clearable
              :options="tcOptions"
              :props="cascaderProps"
              collapse-tags
              style="width: 100%"
              @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleExport">
            <el-icon style="vertical-align: middle">
             <Download />
            </el-icon>查询并导出
          </el-button>
          <ResetButton @click="handleReset"></ResetButton>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import ResetButton from '@/components/Buttons/ResetButton.vue';
import { useTmStore } from '@/stores/tm-module';
import { fetchAllTmList } from '@/api/loads-api'
import { downloadTcApi } from '@/api/search-api'
import { failedNotify, successNotify, downloadFile, deepClone } from '@/comm/index.js'
import { onBeforeMount, ref } from 'vue'
import moment from 'moment'

const exportTmRef = ref(null)
const tmStore = useTmStore()
const emit = defineEmits(['search'])
const checkAll = ref(false)
const indeterminate = ref(false)
let tcOptions = ref([])
let searchForm = ref({
  timeRange: '',
  ids: [{name: '', filters: []}],
  names: []
})
const rules = {
  timeRange: [
   { required: true, message: '必填项', trigger: 'blur' }
  ],
  names: { required: true, message: '必填项', trigger: 'blur' }
}
const cascaderProps = { expandTrigger: 'hover', multiple: true }
let selectedNames = ref([])

const handleCheckAll = (val) => {
  indeterminate.value = false
  if (val) {
    searchForm.value.names = tcOptions.value.map((_) => _.name)
  } else {
    searchForm.vakue.names = []
  }
}
const assmbleReq = (namesArr) => {
  let res = []
  for(const item of namesArr) {
    res.push({
      'name': item[1]
    })
  }
  return res
}
const handleExport = async() => {
  let reqJson = deepClone(searchForm.value)
  await exportTmRef.value.validate((valid, fields) => {
    if(valid) {
      let start= moment(searchForm.value.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
      let end= moment(searchForm.value.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')

      reqJson = { ...reqJson, ...{start, end} }
      reqJson['ids'] = assmbleReq(reqJson.names)
      delete reqJson.names
      delete reqJson.timeRange
      downloadTcApi(reqJson, (response) => {
        downloadFile(response)
      }, (error) => {
        console.log("error:", error)
        failedNotify(error)
      })
    }
  })
}

const handleReset = () => {
  searchForm.value = {
    timeRange: '',
    ids: [{name: '', filters: []}],
    names: []
  }
}

const searchTm = () => {
    fetchAllTmList({}, (response) => {
      const resData = response.data.excel.sheets
      let tcList = []
      for (let i = 0; i < resData.length; i++) {
        let rootTree = {
          label: resData[i].name ,
          value: resData[i].name,
          children: []
        }
        const rows = resData[i].rows
        for (let j = 1; j < rows.length; j++) {
          const row = rows[j]
          const childTree = {
            label: row.name + '（' + row.description + '）',
            value: row.name
          }
          rootTree.children.push(childTree)
        }
        tcList.push(rootTree)
      }
      tcOptions.value = tcList
    }, (error) => {
      console.log("error:", error)
    })
}

const handleChange = (value) => {
  if (selectedNames.value.length === 0) {
    selectedNames.value = deepClone(value)
  }  else {
    if (value.length > 0) {
      const newCategory = value.slice(-1)[0][0]
      const oldCategory = selectedNames.value.slice(-1)[0][0]
      if (newCategory !== oldCategory) {
        searchForm.value.names = searchForm.value.names.splice(0, selectedNames.value.length )
        failedNotify('只能选择同一层级')
      }
    } else {
      selectedNames.value = deepClone(value)
    }
  }
}

onBeforeMount(() => {
  searchTm()
})
</script>

<style lang="scss" scoped>
.cascader-div {
  width: 100%;
}
</style>